class WebSocketClient {

  constructor(messageHandler = null) {
    this.url = import.meta.env.VITE_NODE_ENV == "development" ? import.meta.env.VITE_WEB_URL : window._CONFIG_.VITE_WEB_URL;
    this.socket = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectInterval = 3000; // 3秒重连间隔
    this.messageHandler = messageHandler; // 消息处理函数
  }

  // 初始化并连接 WebSocket
  connect() {

    // 优化：如果已有连接，先清理并关闭
    if (this.socket) {
      // 移除事件监听器避免循环触发
      this.socket.onopen = null;
      this.socket.onmessage = null;
      this.socket.onerror = null;
      this.socket.onclose = null;
      // 关闭现有连接
      this.socket.close();
      this.socket = null;
    }

    this.socket = new WebSocket(this.url);

    this.socket.onopen = () => {
      console.log('WebSocket 连接已建立');
      this.reconnectAttempts = 0;
    };

    this.socket.onmessage = (event) => {
      console.log('收到消息:', event.data);
      if (this.messageHandler) {
        this.messageHandler(event.data); // 调用自定义消息处理函数
      }
    };

    this.socket.onclose = () => {
      console.log('WebSocket 连接已关闭');
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        setTimeout(() => {
          this.reconnectAttempts++;
          console.log(`尝试第 ${this.reconnectAttempts} 次重连...`);
          this.connect();
        }, this.reconnectInterval);
      } else {
        console.log('WebSocket 连接失败');
      }
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket 发生错误:', error);
    };
  }

  // 发送消息
  send(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    } else {
      console.error('无法发送消息，WebSocket 连接未就绪');
    }
  }

  // 关闭连接
  close() {
    if (this.socket) {
      this.socket.close();
    }
  }
}

// 导出 WebSocketClient 类，方便调用
export default WebSocketClient;




// 以下是 WebSocketClient 类的使用示例
// const messageHandler = (data) => {
//   console.log('自定义消息处理:', data);
// };

// const client = new WebSocketClient(messageHandler);
// client.connect();

// // 示例发送消息
// setTimeout(() => {
//   client.send('Hello, WebSocket!');
// }, 2000);

// // 示例关闭连接
// setTimeout(() => {
//   client.close();
// }, 10000);
